<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus12.html">Previous Chapter</a>
    <li> <a href="cplusplus14.html">Next Chapter</a>
</ul>
<hr>
<a name="INHERITANCE"></a><a name="l188"></a>
<h1>Chapter 13: Inheritance</h1>
<a name="inheritance"></a>

<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="inheritance/intro"></a>When programming in <strong>C</strong>, programming problems are commonly approached using
a top-down structured approach: functions and actions of the program are
defined in terms of sub-functions, which again are defined in
sub-sub-functions, etc..  This yields a <a name="an1822"></a>
hierarchy of code: <code>main()</code> at
the top, followed by a level of functions which are called from <code>main()</code>,
etc..
<p>
In <strong>C++</strong> the <a name="an1823"></a>
dependencies between code and data is also frequently defined
in terms of dependencies among <em>classes</em>. This looks like <a name="an1824"></a>
<em>composition</em>
(see section <a href="cplusplus06.html#Composition">6.4</a>), where objects of a class contain objects of
another class as their data. But the relation described here is of a different
kind: a class can be <em>defined</em> in terms of an older, pre-existing,
class. This produces a new class having all the functionality of the older
class, and additionally introducing its own specific functionality.  Instead
of composition, where a given class <em>contains</em> another class, we here refer
to <a name="an1825"></a>
<em>derivation</em>, where a given class <em>is</em> another class.
<p>
Another term for derivation is <a name="an1826"></a>
<em>inheritance</em>: the new class inherits the
functionality of an existing class, while the existing class does not appear
as a data member in the definition of the new class. When discussing
inheritance the existing class is called the <a name="an1827"></a>
<em>base class</em>, while the new
class is called the <a name="an1828"></a>
<em>derived class</em>.
<p>
Derivation of classes is often used when the methodology of <strong>C++</strong>
        <a name="an1829"></a>
program development
    is fully exploited. In this chapter we will first address the syntactical
possibilities offered by <strong>C++</strong> for deriving classes from other classes. Then
we will address some of the resulting possibilities.
<p>
As we have seen in the introductory chapter (see section <a href="cplusplus02.html#OOP">2.4</a>), in the
<a name="an1830"></a>
object-oriented approach to problem solving classes are identified during
the <a name="an1831"></a>
problem analysis, after which objects of the defined classes represent
entities of the problem at hand. The classes are placed in a hierarchy, where
the top-level class contains the least functionality.  Each new derivation
(and hence descent in the <a name="an1832"></a>
class hierarchy) adds new functionality compared
to yet existing classes.
<p>
In this chapter we shall use a simple vehicle classification system to build a
hierarchy of classes. The first class is <code>Vehicle</code>, which implements as its
functionality the possibility to set or retrieve the weight of a vehicle. The
next level in the object hierarchy are land-, water- and air vehicles.
<p>
The initial <a name="an1833"></a>
object hierarchy is illustrated in Figure <a href="cplusplus13.html#hierarchy">12</a>.
    <a name="hierarchy"></a><p><center><img src="inheritance/hierarchy.gif" align="bottom" alt="Figure 12 is shown here."/><br>
Figure 12: Initial object hierarchy of vehicles.
</center><p><br>

<p>
<a name="VehicleSystem"></a><a name="l189"></a>
<h2>13.1: Related types</h2>
    <a name="inheritance/related"></a>The relationship between the proposed classes representing different kinds of
vehicles is further illustrated here. The figure shows the object hierarchy:
an <code>Auto</code> is a special case of a <code>Land</code> vehicle, which in turn is a
special case of a <code>Vehicle</code>.
<p>
The class <code>Vehicle</code> is thus the `<a name="an1834"></a>
greatest common denominator' in the
classification system. For the sake of the example in this class we implement
the functionality to store and retrieve the vehicle's weight:
        <pre>
    class Vehicle
    {
        size_t d_weight;

        public:
            Vehicle();
            Vehicle(size_t weight);

            size_t weight() const;
            void setWeight(size_t weight);
    };
</pre>
    Using this class, the vehicle's weight can be defined as soon as the
corresponding object has been created. At a later stage the weight can be
re-defined or retrieved.
<p>
To represent vehicles which travel over land, a new class <code>Land</code> can be
defined with the functionality of a <code>Vehicle</code>, while adding its own specific
information and functionality. Assume that we are interested in the speed of
land vehicles <em>and</em> in their weights. The relationship between <code>Vehicle</code>s
and <code>Land</code>s could of course be represented using composition, but that would
be awkward: composition would suggest that a <code>Land</code> vehicle <em>contains</em> a
vehicle, while the relationship should be that the <code>Land</code> vehicle <em>is</em> a
special case of a vehicle.
<p>
A relationship in terms of composition would also needlessly bloat our code.
E.g., consider the following code fragment which shows a class <code>Land</code> using
composition (only the <code>setWeight()</code> functionality is shown):
        <pre>
    class Land
    {
        Vehicle d_v;        // composed Vehicle
        public:
            void setWeight(size_t weight);
    };

    void Land::setWeight(size_t weight)
    {
        d_v.setWeight(weight);
    }
</pre>
    Using composition, the <code>setWeight()</code> function of the class <code>Land</code> only
serves to pass its argument to <code>Vehicle::setWeight()</code>. Thus, as far as
weight handling is concerned, <code>Land::setWeight()</code> introduces no extra
functionality, just extra code. Clearly this code duplication is superfluous:
a <code>Land</code> should <em>be</em> a <code>Vehicle</code>; it should not <em>contain</em>
a <code>Vehicle</code>.
<p>
The intended relationship is achieved better by <a name="an1835"></a>
inheritance:
<code>Land</code> is <em>derived</em> from <code>Vehicle</code>, in which <code>Vehicle</code> is the
    derivation's <a name="an1836"></a>
base class:
        <pre>
    class Land: public Vehicle
    {
        size_t d_speed;
        public:
            Land();
            Land(size_t weight, size_t speed);

            void setspeed(size_t speed);
            size_t speed() const;
    };
</pre>
    By postfixing the class name <code>Land</code> in its definition by <code>: public
Vehicle</code> the <a name="an1837"></a>
derivation is realized: the class <code>Land</code> now contains all
the functionality of its base class <code>Vehicle</code> plus its own specific
information and functionality. The extra functionality consists of a
constructor with two arguments and interface functions to access the <code>speed</code>
data member. In the above example <a name="an1838"></a>
<em>public derivation</em> is used.
<strong>C++</strong> also supports
    <a name="an1839"></a>
<em>private derivation</em> and <a name="an1840"></a>
<em>protected derivation</em>. In section
<a href="cplusplus13.html#DERIVATIONTYPES">13.6</a> their differences are discussed.  A simple example
showing the possibilities of of the derived class <code>Land</code> is:
        <pre>
    Land veh(1200, 145);

    int main()
    {
        cout &lt;&lt; "Vehicle weighs " &lt;&lt; veh.weight() &lt;&lt; endl
             &lt;&lt; "Speed is " &lt;&lt; veh.speed() &lt;&lt; endl;
    }
</pre>
    This example shows two features of derivation. First, <code>weight()</code> is not
mentioned as a member in <code>Land</code>'s interface. Nevertheless it is used in
<code>veh.weight()</code>.  This member function is an implicit part of the class,
inherited from its `<a name="an1841"></a>
parent' vehicle.
<p>
Second, although the derived class <code>Land</code> now contains the functionality of
<code>Vehicle</code>, the <a name="an1842"></a>
private fields of <code>Vehicle</code> remain private: they can
only be accessed by <code>Vehicle</code>'s own member functions. This means that
<code>Land</code>'s member functions <em>must</em> use interface functions (like
<code>weight()</code> and <code>setWeight()</code>) to address the <code>weight</code> field, just as any
other code outside the <code>Vehicle</code> class. This restriction is necessary to
enforce the principle of <a name="an1843"></a>
data hiding. The class <code>Vehicle</code> could, e.g., be
recoded and recompiled, after which the program could be relinked. The class
<code>Land</code> itself could remain unchanged.
<p>
Actually, the previous remark is not quite right: If the
    <a name="an1844"></a>
internal organization of <code>Vehicle</code> changes, then the internal
organization of <code>Land</code> objects, containing the data of <code>Vehicle</code>, changes
as well. This means that objects of the <code>Land</code> class, after changing
<code>Vehicle</code>, might require more (or less) memory than before the
modification. However, in such a situation we still don't have to worry about
member functions of the parent class (<code>Vehicle</code>) in the class <code>Land</code>. We
might have to recompile the <code>Land</code> sources, though, as the relative
locations of the <a name="an1845"></a>
data members within the <code>Land</code> objects will have changed
due to the modification of the <code>Vehicle</code> class.
<p>
As a <a name="an1846"></a>
rule of thumb, classes which are derived from other classes must be
fully recompiled (but don't have to be modified) after changing the <em>data
organization</em>, i.e., the data members, of their base classes.  As adding new
member <em>functions</em> to the base class doesn't alter the data organization, no
<a name="an1847"></a>
recompilation is needed after adding new member <em>functions</em>. (A subtle
point to note, however, is that adding a new member function that happens to
be the <em>first</em> <a href="cplusplus14.html#virfunc"><em>virtual</em> member function</a> of a class results
in a new data member: a <a href="cplusplus14.html#howpolymorfism">hidden pointer</a> to a table of
pointers to virtual functions. So, in this case recompilation is also
necessary, as the class's data members have been silently modified. This topic
is discussed further in chapter <a href="cplusplus14.html#POLYMORPHISM">14</a>).
<p>
In the following example we assume that the class <code>Auto</code>, representing
automobiles, should contain the weight, speed and name of a car.
This class is conveniently derived from <code>Land</code>:
        <pre>
    class Auto: public Land
    {
        char *d_name;

        public:
            Auto();
            Auto(size_t weight, size_t speed, char const *name);
            Auto(Auto const &amp;other);

            ~Auto();

            Auto &amp;operator=(Auto const &amp;other);

            char const *name() const;
            void setName(char const *name);
    };
</pre>
    In the above class definition, <code>Auto</code> is derived from <code>Land</code>, which in
turn is derived from <code>Vehicle</code>. This is called <a name="an1848"></a>
<em>nested derivation</em>:
<code>Land</code> is called <code>Auto</code>'s <a name="an1849"></a>
<em>direct base class</em>, while <code>Vehicle</code> is
called the <a name="an1850"></a>
<em>indirect base class</em>.
<p>
Note the presence of a <a name="an1851"></a>
destructor, a <a name="an1852"></a>
copy constructor and an
    <a name="an1853"></a>
overloaded assignment operator in the class <code>Auto</code>. Since this class
uses a pointer to reach <a name="an1854"></a>
dynamically allocated memory, these members should
be part of the <a name="an1855"></a>
class interface.
<p>
<a name="l190"></a>
<h2>13.2: The constructor of a derived class</h2>
    <a name="inheritance/constructor"></a>As mentioned earlier, a derived class inherits the functionality from its
<a name="an1856"></a>
base class. In this section we shall describe the effects
    <a name="an1857"></a>
inheritance has on the constructor of a derived class.
<p>
As will be clear from the definition of the class <code>Land</code>, a <a name="an1858"></a>
constructor
exists to set both the <code>weight</code> and the <code>speed</code> of an object. The
poor-man's implementation of this constructor could be:
        <pre>
    Land::Land (size_t weight, size_t speed)
    {
        setWeight(weight);
        setspeed(speed);
    }
</pre>
    This implementation has the following disadvantage. The <strong>C++</strong> compiler
will generate code calling the base class's <a name="an1859"></a>
default constructor from each
constructor in the <a name="an1860"></a>
derived class, unless explicitly instructed otherwise.
This can be compared to the situation we encountered in composed objects (see
section <a href="cplusplus06.html#Composition">6.4</a>).
<p>
Consequently, in the above implementation the
    <a name="an1861"></a>
default constructor of <code>Vehicle</code> is called, which probably
initializes the weight of the vehicle, only to be redefined immediately
thereafter by the function <code>setWeight()</code>.
<p>
A more efficient approach is of course to call the constructor of
<code>Vehicle</code> expecting an <code>size_t weight</code> argument directly.  The syntax
achieving this is to mention the constructor to be called (supplied with its
arguments) immediately following the argument list of the constructor of the
derived class itself. Such a <a name="an1862"></a>
base class initializer is shown in the next
example. Following the constructor's head a colon appears, which is then
followed by the base class constructor. Only then any member initializer may
be specified (using commas to separate multiple initializers), followed by the
constructor's body:
        <pre>
    Land::Land(size_t weight, size_t speed)
    :
        Vehicle(weight)
    {
        setspeed(speed);
    }
</pre>
<p>
<a name="l191"></a>
<h2>13.3: The destructor of a derived class</h2>
    <a name="inheritance/destructor"></a>Destructors of classes are automatically called when an object is
destroyed. This also holds true for objects of classes derived from other
classes. Assume we have the following situation:
        <pre>
    class Base
    {
        public:
            ~Base();
    };

    class Derived: public Base
    {
        public:
            ~Derived();
    };

    int main()
    {
        Derived
            derived;
    }
</pre>
    At the end of the <code>main()</code> function, the <code>derived</code> object ceases to
exists. Hence, its <a name="an1863"></a>
destructor (<code>~Derived()</code>) is called. However, since
<code>derived</code> is also a <code>Base</code> object, the <code>~Base()</code> destructor is called as
well.  It is <em>not</em> neccessary to call the base class destructor explicitly
from the derived class destructor.
<p>
Constructors <a name="an1864"></a>
 <a name="an1865"></a>
 and
destructors are called in a stack-like fashion: when <code>derived</code> is
constructed, the appropriate base class constructor is called first, then the
appropriate derived class constructor is called. When the object <code>derived</code>
is destroyed, its destructor is called first, automatically followed by the
activation of the <code>Base</code> class destructor. A <a name="an1866"></a>
derived class destructor is
always called before its <a name="an1867"></a>
base class destructor is called.
<p>
<a name="Truck"></a><a name="l192"></a>
<h2>13.4: Redefining member functions</h2>
    <a name="inheritance/redefining"></a>The functionality of all members of a <a name="an1868"></a>
base class (which
    <a name="an1869"></a>
 <a name="an1870"></a>
 are
therefore also available in derived classes) can be redefined. This feature is
illustrated in this section.
<p>
Let's assume that the vehicle classification system should be able to
represent trucks, consisting of two parts: the front engine, pulling the
second part, a trailer. Both the front engine and the trailer have their own
weights, and the <code>weight()</code> function should return the combined weight.
<p>
The definition of a <code>Truck</code> therefore starts with the class definition,
derived from <code>Auto</code> but it is then expanded to hold one more <code>size_t</code> field
representing the additional weight information. Here we choose to represent
the weight of the front part of the truck in the <code>Auto</code> class and to store
the weight of the trailer in an additional field:
        <pre>
    class Truck: public Auto
    {
        size_t d_trailer_weight;

        public:
            Truck();
            Truck(size_t engine_wt, size_t speed, char const *name,
                  size_t trailer_wt);

            void setWeight(size_t engine_wt, size_t trailer_wt);
            size_t weight() const;
    };

    Truck::Truck(size_t engine_wt, size_t speed, char const *name,
                 size_t trailer_wt)
    :
        Auto(engine_wt, speed, name)
    {
        d_trailer_weight = trailer_wt;
    }
</pre>
    Note that the class <code>Truck</code> now contains two functions already
present in the base class <code>Auto</code>: <code>setWeight()</code> and <code>weight()</code>.
    <ul>
    <li> The redefinition of <code>setWeight()</code> poses no problems: this
function is simply redefined to perform actions which are specific to a
<code>Truck</code> object.
    <li> The redefinition of <code>setWeight()</code>, however, will
    <a name="an1871"></a>
 <a name="an1872"></a>
 <em>hide</em>
<code>Auto::setWeight()</code>: for a <code>Truck</code> only the <code>setWeight()</code> function
having two <code>size_t</code> arguments can be used.
    <li> The <code>Vehicle</code>'s <code>setWeight()</code> function remains available for a
<code>Truck</code>, but it <em>must</em> now be <a name="an1873"></a>

called <em>explicitly</em>, as <code>Auto::setWeight()</code>
is now hidden from view.
This latter function is hidden,
even though <code>Auto::setWeight()</code> has only one <code>size_t</code> argument. To
implement <code>Truck::setWeight()</code> we could write:
         <pre>
    void Truck::setWeight(size_t engine_wt, size_t trailer_wt)
    {
        d_trailer_weight = trailer_wt;
        Auto::setWeight(engine_wt);     // note: Auto:: is required
    }
</pre>
    <li> Outside of the class the <code>Auto</code>-version of <code>setWeight()</code> is
accessed using the <a name="an1874"></a>
scope resolution operator. So, if a <code>Truck t</code> needs
to set its <code>Auto</code> weight, it must use
        <pre>
    t.Auto::setWeight(x);
</pre>
    <li> An alternative to using the scope resolution operator is to include
explicitly a member having the same
    <a name="an1875"></a>
function prototype as the base class member. This derived class member
may then be implemented inline to call the base class member. This might be an
elegant solution for the occasional situation. E.g., we add the following
member to the <code>class Truck</code>:
        <pre>
    // in the interface:
    void setWeight(size_t engine_wt);

    // below the interface:
    inline void Truck::setWeight(size_t engine_wt)
    {
        Auto::setWeight(engine_wt);
    }
</pre>
    Now the single argument <code>setWeight()</code> member function can be used by
<code>Truck</code> objects without having to use the scope resolution operator. As the
function is defined inline, no overhead of an additional function call is
involved.
    <li> The function <code>weight()</code> is also already defined in <code>Auto</code>, as
it was inherited from <code>Vehicle</code>. In this case, the class <code>Truck</code> should
<em>redefine</em> this member function to allow for the extra (trailer) weight in
the <code>Truck</code>:
         <pre>
    size_t Truck::weight() const
    {
        return
            (                           // sum of:
                Auto::weight() +     //   engine part plus
                d_trailer_weight        //   the trailer
            );
    }
</pre>
    </ul>
    The next example shows the actual use of the member functions of the
class <code>Truck</code>, displaying several weights:
        <pre>
    int main()
    {
        Land veh(1200, 145);
        Truck lorry(3000, 120, "Juggernaut", 2500);

        lorry.Vehicle::setWeight(4000);

        cout &lt;&lt; endl &lt;&lt; "Truck weighs " &lt;&lt;
                        lorry.Vehicle::weight() &lt;&lt; endl &lt;&lt;
            "Truck + trailer weighs " &lt;&lt; lorry.weight() &lt;&lt; endl &lt;&lt;
            "Speed is " &lt;&lt; lorry.speed() &lt;&lt; endl &lt;&lt;
            "Name is " &lt;&lt; lorry.name() &lt;&lt; endl;
    }
</pre>
    Note the explicit call of <code>Vehicle::setWeight(4000)</code>: assuming
<code>setWeight(size_t engine_wt)</code> is not part of the interface of the class
<code>Truck</code>, it <em>must</em> be called explicitly, using the <code>Vehicle::</code> scope
resolution, as the single argument function <code>setWeight()</code> is hidden from
direct view in the class <code>Truck</code>.
<p>
With <code>Vehicle::weight()</code> and <code>Truck::weight()</code> the situation is
somewhat different: here the function <code>Truck::weight()</code> is a
<em>redefinition</em> of <code>Vehicle::</code><code>weight()</code>, so in order to reach 
<code>Vehicle::weight()</code> a scope resolution operation (<code>Vehicle::</code>) is
required.
<p>
<a name="MULTIPLE"></a><a name="l193"></a>
<h2>13.5: Multiple inheritance</h2>
    <a name="inheritance/multiple"></a>Up to now, a class was always derived from <em>a single</em> <a name="an1876"></a>
base class. <strong>C++</strong>
also supports <a name="an1877"></a>
<em>multiple derivation</em>, in which a class is derived
from several base classes and hence inherits functionality of
        <a name="an1878"></a>
multiple parent classes at the same time.
    In cases where <a name="an1879"></a>
multiple inheritance is considered, it should be
defensible to consider the newly derived class an instantiation of both base
classes. Otherwise, <a name="an1880"></a>
composition might be more appropriate. In general,
<a name="an1881"></a>
linear derivation, in which there is only one base class, is used much more
frequently than multiple derivation. Most objects have a primary purpose, and
that's it. But then, consider <em>the</em> prototype of an object for which
multiple inheritance was used to its extreme: the
    <a name="an1882"></a>
<em>Swiss army knife</em>! This object <em>is</em> a knife, it <em>is</em> a pair of
scissors, it <em>is</em> a can-operner, it <em>is</em> a corkscrew, it <em>is</em> ....
<p>
How can we construct a `Swiss army knife' in <strong>C++</strong>? First we need (at
least) two base classes. For example, let's assume we are designing a toolkit
allowing us to construct an instrument panel of an aircraft's cockpit. We
design all kinds of instruments, like an artifical horizon and an
altimeter. One of the components that is often seen in aircraft is a
<a name="an1883"></a>
<em>nav-com set</em>: a combination of a navigational beacon receiver (the `nav'
part) and a radio communication unit (the `com'-part). To define the nav-com
set, we first design the <code>NavSet</code> class. For the time being, its data
members are omitted:
        <pre>
    class NavSet
    {
        public:
            NavSet(Intercom &amp;intercom, VHF_Dial &amp;dial);

            size_t activeFrequency() const;
            size_t standByFrequency() const;

            void setStandByFrequency(size_t freq);
            size_t toggleActiveStandby();
            void setVolume(size_t level);
            void identEmphasis(bool on_off);
    };
</pre>
    In the class'ss contructor we assume the availability of the classes
<code>Intercom</code>, which is used by the pilot to listen to the information
transmitted by the navigational beacon, and a class <code>VHF_Dial</code> which is used
to represent visually what the <code>NavSet</code> receives.
<p>
Next we construct the <code>ComSet</code> class. Again, omitting the data members:
        <pre>
    class ComSet
    {
        public:
            ComSet(Intercom &amp;intercom);

            size_t frequency() const;
            size_t passiveFrequency() const;

            void setPassiveFrequency(size_t freq);
            size_t toggleFrequencies();

            void setAudioLevel(size_t level);
            void powerOn(bool on_off);
            void testState(bool on_off);
            void transmit(Message &amp;message);
    };
</pre>
    Using objects of this class we can receive messages, transmitted
though the <code>Intercom</code>, but we can also <em>transmit</em> messages, using a
<code>Message</code> object that's passed to the <code>ComSet</code> object using its
<code>transmit()</code> member function.
<p>
Now we're ready to construct the <code>NavCom</code> set:
        <pre>
    class NavComSet: public ComSet, public NavSet
    {
        public:
            NavComSet(Intercom &amp;intercom, VHF_Dial &amp;dial);
    };
</pre>
    Done. Now we have defined a <code>NavComSet</code> which is <em>both</em> a <code>NavSet</code>
<em>and</em> a <code>ComSet</code>: the possibilities of either <a name="an1884"></a>
base class are now
available in the <a name="an1885"></a>
derived class, using <a name="an1886"></a>
multiple derivation.
<p>
With multiple derivation, please note the following:
    <ul>
    <li> The keyword <a name="an1887"></a>
<code>public</code> is present before both base class names
(<code>NavSet</code> and <code>ComSet</code>). This is so because the default derivation
in <strong>C++</strong> is <a name="an1888"></a>
<code>private</code>: the keyword <code>public</code> must be repeated before each
base class specification. The base classes do not have to have the same kind
of derivation: one base class could have <code>public</code> derivation, another base
class could use <a name="an1889"></a>
<code>protected</code> derivation, yet another base class could use
<code>private</code> derivation.
    <li> The multiply derived class <code>NavComSet</code> introduces no
    <a name="an1890"></a>
additional functionality of its own, but merely combines two existing
classes into a new <a name="an1891"></a>
aggregate class. Thus, <strong>C++</strong> offers the possibility to
simply sweep multiple simple classes into one more complex class.
<p>
This feature of <strong>C++</strong> is often used. Usually it pays to develop
`simple' classes each having a simple, well-defined functionality.  More
complex classes can always be constructed from these simpler
        <a name="an1892"></a>
building blocks.
    <li> Here is the implementation of The <code>NavComSet</code> <a name="an1893"></a>
constructor:
        <pre>
    NavComSet::NavComSet(Intercom &amp;intercom, VHF_Dial &amp;dial)
    :
        ComSet(intercom),
        NavSet(intercom, VHF_Dial)
    {}
</pre>
    The constructor requires no extra code: Its only purpose is to activate
the constructors of its base classes. The order in which the base class
initializers <a name="an1894"></a>

    <a name="an1895"></a>
 are called is <em>not</em>
dictated by their calling order in the constructor's code, but by the ordering
of the base classes in the class interface.
    <li> the <code>NavComSet</code> class definition needs no extra data members or
member functions: here (and often) the inherited interfaces provide all the
required functionality and data for the multiply derived class to operate
properly.
    </ul>
    Of course, while defining the base classes, we made life easy on ourselves
by strictly using different member function names. So, there is a function
<code>setVolume()</code> in the <code>NavSet</code> class and a function <code>setAudioLevel()</code> in
the <code>ComSet</code> class. A bit <a name="an1896"></a>
cheating, since we could expect that both units
in fact have a composed object <code>Amplifier</code>, handling the volume setting. A
revised class might then either use a <code>Amplifier &amp;amplifier() const</code> member
function, and leave it to the application to set up its own interface to the
amplifier, or access functions for, e.g., the volume are made available
through the <code>NavSet</code> and <code>ComSet</code> classes as, normally, member functions
having the same names (e.g., <code>setVolume()</code>). In situations where two base
classes use the same member function <a name="an1897"></a>

    <a name="an1898"></a>
 names, special provisions need to
be made to prevent <a name="an1899"></a>
ambiguity:
    <ul>
    <li> The intended base class can explicitly be specified, using the base
class name and <a name="an1900"></a>
scope resolution operator in combination with the doubly
occurring member function name:
        <pre>
    NavComSet navcom(intercom, dial);

    navcom.NavSet::setVolume(5);    // sets the NavSet volume level
    navcom.ComSet::setVolume(5);    // sets the ComSet volume level
</pre>
    <li> The class interface is extended by member functions which do the
explicitation for the user of the class. These additional members will
normally be defined as <code>inline</code>:
        <pre>
    class NavComSet: public ComSet, public NavSet
    {
        public:
            NavComSet(Intercom &amp;intercom, VHF_Dial &amp;dial);
            void comVolume(size_t volume);
            void navVolume(size_t volume);
    };
    inline void NavComSet::comVolume(size_t volume)
    {
        ComSet::setVolume(volume);
    }
    inline void NavComSet::navVolume(size_t volume)
    {
        NavSet::setVolume(volume);
    }
</pre>
    <li> If the <code>NavComSet</code> class is obtained from a third party, and should
not be altered, a <a name="an1901"></a>
wrapper class could be used, which does the previous
explicitation for us in our own programs:
        <pre>
    class MyNavComSet: public NavComSet
    {
        public:
            MyNavComSet(Intercom &amp;intercom, VHF_Dial &amp;dial);
            void comVolume(size_t volume);
            void navVolume(size_t volume);
    };
    inline MyNavComSet::MyNavComSet(Intercom &amp;intercom, VHF_Dial &amp;dial)
    :
        NavComSet(intercom, dial);
    {}
    inline void MyNavComSet::comVolume(size_t volume)
    {
        ComSet::setVolume(volume);
    }
    inline void MyNavComSet::navVolume(size_t volume)
    {
        NavSet::setVolume(volume);
    }
</pre>
    </ul>
<p>
<a name="DERIVATIONTYPES"></a><a name="l194"></a>
<h2>13.6: Public, protected and private derivation</h2>
    <a name="inheritance/derivationtypes"></a>As we've seen, classes may be derived from other classes using
inheritance. Usually the <a name="an1902"></a>
derivation type is <a name="an1903"></a>
<code>public</code>, implying that the
access rights of the base class's interface is unaltered in the derived class.
<p>
Apart from <a name="an1904"></a>
public derivation, <strong>C++</strong> also supports
    <a name="an1905"></a>
<em>protected derivation</em> and <a name="an1906"></a>
<em>private derivation</em>
<p>
To use protected derivation. the keyword <code>protected</code> is specified in the
inheritance list:
        <pre>
    class Derived: protected Base
</pre>
    With protected derivation all the base class's public and protected members
receive protected access rights in the derived class. Members having protected
access rights are available to the class itself and to all classes that are
(directly or indirectly) derived from it.
<p>
To use private derivation. the keyword <code>private</code> is specified in the
inheritance list:
        <pre>
    class Derived: private Base
</pre>
    With private derivation all the base class's  members
receive private access rights in the derived class. Members having private
access rights are only available to the class itself.
<p>
Combinations of inheritance types do occur. For example, when designing a
stream-class it is usually derived from <code>std::istream</code> or
<code>std::ostream</code>. However, before a stream can be constructed, a
<code>std::streambuf</code> must be available. Taking advantage of the fact that the
inheritance order is taken seriously by the compiler, we can use multiple
inheritance (see section <a href="cplusplus13.html#MULTIPLE">13.5</a>) to derive the class from both
<code>std::streambuf</code> and (then) from, e.g., <code>std::ostream</code>. As our class faces
its clients as a <code>std::ostream</code> and not as a <code>std::streambuf</code>, we use
private derivation for the latter, and public derivation for the former class:
        <pre>
    class Derived: private std::streambuf, public std::ostream
</pre>
<p>
<a name="l195"></a>
<h2>13.7: Conversions between base classes and derived classes</h2>
    <a name="inheritance/conversions"></a>When inheritance is used to define classes, it can be said that an object of a
derived class <em>is</em> at the same time an object of the base class.  This has
important consequences for the assignment of objects, and for the situation
where pointers or references to such objects are used. Both situations will be
discussed next.
<p>
<a name="l196"></a>
<h3>13.7.1: Conversions in object assignments</h3>
        <a name="inheritance/objectconv"></a>Continuing our discussion of the <code>NavCom</code> class, introduced in section
<a href="cplusplus13.html#MULTIPLE">13.5</a> We start by defining two objects, a base class and a derived
class object:
        <pre>
    ComSet com(intercom);
    NavComSet navcom(intercom2, dial2);
</pre>
    The object <code>navcom</code> is constructed using an <code>Intercom</code> and a <code>Dial</code>
object. However, a <code>NavComSet</code> is at the same time a <code>ComSet</code>, allowing
the <a name="an1907"></a>
assignment <em>from</em> <code>navcom</code> (a derived class object) <em>to</em> <code>com</code>
(a base class object):
        <pre>
    com = navcom;
</pre>
    The effect of this assignment should be that the object <code>com</code> will now
communicate with <code>intercom2</code>.  As a <code>ComSet</code> does not have a <code>VHF_Dial</code>,
the <code>navcom</code>'s <code>dial</code> is ignored by the assignment: when assigning a
base class object from a derived class object only the base class data members
are assigned, other data members are ignored.
<p>
The assignment from a base class object to a derived class object,
however, is problematic: In a statement like
        <pre>
    navcom = com;
</pre>
    it isn't clear how to reassign the <code>NavComSet</code>'s <code>VHF_Dial</code> data
member as they are missing in the <code>ComSet</code> object <code>com</code>. Such an
assignment <a name="an1908"></a>
 is therefore refused by the
compiler. Although derived class objects are also base class objects, the
reverse does not hold true: a base class object is not also a derived class
object.
<p>
The following <a name="an1909"></a>
general rule applies: in assignments in which base class
objects and derived class objects are involved, assignments in which data are
dropped is legal. However, assignments in which data would remain unspecified
is <em>not</em> allowed.  Of course, it is possible to redefine an overloaded
<a name="an1910"></a>
assignment operator to allow the assignment of a derived class object by a
base class object.  E.g., to achieve compilability of a statement
        <pre>
    navcom = com;
</pre>
    the class <code>NavComSet</code> must have an overloaded assignment operator
 function accepting a <code>ComSet</code> object for its argument. It would be the
responsibility of the programmere constructing the assignment operator to
decide what to do with the missing data.
<p>
<a name="l197"></a>
<h3>13.7.2: Conversions in pointer assignments</h3>
        <a name="inheritance/pointerconv"></a>    We return to our <code>Vehicle</code> classes, and define the following objects and
pointer variable:
        <pre>
    Land land(1200, 130);
    Auto auto(500, 75, "Daf");
    Truck truck(2600, 120, "Mercedes", 6000);
    Vehicle *vp;
</pre>
    Now we can assign the  addresses of the three objects of
the derived classes to the <code>Vehicle</code> pointer:
        <pre>
    vp = &amp;land;
    vp = &amp;auto;
    vp = &amp;truck;
</pre>
    Each of these assignments is acceptable. However, an
    <a name="an1911"></a>
implicit conversion of the <a name="an1912"></a>
derived class to the <a name="an1913"></a>
base class
<code>Vehicle</code> is used, since <code>vp</code> is defined as a pointer to a
<code>Vehicle</code>. Hence, when using <code>vp</code> only the member functions manipulating
<code>weight</code> can be called as this is the <code>Vehicle</code>'s <em>only</em> functionality.
As far as the compiler can tell this is the object <code>vp</code> points to.
<p>
The same reasoning holds true for <a name="an1914"></a>
 references to
<code>Vehicles</code>. If, e.g., a function is defined having a <code>Vehicle</code> reference
parameter, the function may be passed an object of a class derived from
<code>Vehicle</code>. Inside the function, the specific <code>Vehicle</code> members remain
accessible. This analogy between pointers and references holds true in
general. Remember that a reference is nothing but a <a name="an1915"></a>
pointer in disguise: it
mimics a plain variable, but actually it is a pointer.
<p>
This <a name="an1916"></a>
restricted functionality furthermore has an important consequence
for the class <code>Truck</code>. After the statement <code>vp = &amp;truck</code>, <code>vp</code> points to
a <code>Truck</code> object. So, <code>vp-&gt;weight()</code> will return 2600 instead of
8600 (the combined weight of the cabin and of the trailer: 2600 + 6000),
which would have been returned by <code>truck.weight()</code>.
<p>
When a function is called using a <a name="an1917"></a>
pointer to an object, then the
    <a name="an1918"></a>
<em>type of the pointer</em> (and not the type of the object) determines
which
    <a name="an1919"></a>

    <a name="an1920"></a>
 member functions are available and
executed.  In other words, <strong>C++</strong> implicitly converts the type of an object
reached through a pointer to the pointer's type.
<p>
If the actual type of the object to which a pointer points is known, an
explicit <a name="an1921"></a>
type cast can be used to access the full set of member functions
that are available for the object:
        <pre>
    Truck truck;
    Vehicle *vp;

    vp = &amp;truck;        // vp now points to a truck object

    Truck *trp;

    trp = reinterpret_cast&lt;Truck *&gt;(vp);
    cout &lt;&lt; "Make: " &lt;&lt; trp-&gt;name() &lt;&lt; endl;
</pre>
    Here, the second to last statement specifically casts a <code>Vehicle *</code>
variable to a <code>Truck *</code>. As is usually the case with type casts, this code
is not without risk: it will <em>only</em> work if <code>vp</code> really points to a
<code>Truck</code>. Otherwise the program may behave unexpectedly.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus12.html">Previous Chapter</a>
    <li> <a href="cplusplus14.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
